﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json.Linq;
using Sunny.UI;

namespace RclSystem
{
    public partial class ReceiptDialog : UIEditForm
    {
        public ReceiptDialog()
        {
            InitializeComponent();
            dt_receiptdate.Value = DateTime.Now;
            DataTable dt_saleman = MySQLHelper.ExecuteQuery("SELECT * FROM tbl_saleman");
            cb_saleman.DataSource = dt_saleman;
            cb_saleman.DisplayMember = "name";
            cb_saleman.ValueMember = "id";
            cb_saleman.SelectedIndex = -1;
        }

        protected override bool CheckData()
        {
            return CheckEmpty(cb_company, "请输入单位名称") && CheckEmpty(cb_saleman, "请选择业务员") && CheckEmpty(cb_receiptway, "请选择收款方式") && CheckEmpty(dt_receiptdate, "请选择收款日期")
                 && CheckEmpty(txt_interestrate, "请输入利率") && CheckEmpty(txt_receiptamount, "请输入收款金额") && CheckEmpty(txt_overduedays, "请输入逾期天数")
                  && CheckEmpty(txt_interest, "请输入逾期利息");
        }

        private ReceiptEntity receipt;

        public ReceiptEntity ReceiptEntity
        {
            get
            {
                if (receipt == null)
                {
                    receipt = new ReceiptEntity();
                }

                receipt.salesman = cb_saleman.Text;
                receipt.companyname = cb_company.Text;
                receipt.receiptdate = dt_receiptdate.Value;
                receipt.receiptway = cb_receiptway.Text;
                receipt.receiptamount = decimal.Parse(txt_receiptamount.Text);
                receipt.interestrate = double.Parse(txt_interestrate.Text);
                receipt.interest = double.Parse(txt_interest.Text);
                receipt.overduedays = int.Parse(txt_overduedays.Text);
                receipt.parentid = long.Parse(txt_parentid.Text);
                return receipt;
            }

            set
            {
                receipt = value;
                cb_saleman.Text = value.salesman;
                cb_company.Text = value.companyname;
                dt_receiptdate.Value = value.receiptdate;
                cb_receiptway.Text = value.receiptway;
                txt_receiptamount.Text = value.receiptamount.ToString();
                txt_interestrate.Text = value.interestrate.ToString();
                txt_interest.Text = value.interest.ToString();
                txt_overduedays.Text = value.overduedays.ToString();
                txt_parentid.Text = value.parentid.ToString();
            }
        }


        private void cb_saleman_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cb_saleman.SelectedIndex != -1)
            {
                if (cb_saleman.SelectedValue.GetType() != typeof(DataRowView))
                {
                    DataTable dt_company = MySQLHelper.ExecuteQuery("SELECT * FROM tbl_company where parentid = " + cb_saleman.SelectedValue.ToString());
                    cb_company.DataSource = dt_company;
                    cb_company.DisplayMember = "name";
                    cb_company.ValueMember = "id";
                }

            }
        }

        private void dt_receiptdate_ValueChanged(object sender, DateTime value)
        {
            if (dt_receiptdate.Value != null)
            {
                DateTime odt = dt_duedate.Value;
                int diffdays = (dt_receiptdate.Value - odt).Days;
                if(diffdays <= 0)
                {
                    diffdays = 0;
                }
                txt_overduedays.Text = diffdays.ToString();
                txt_interest.Text = Math.Round((decimal.Parse(txt_receiptamount.Text) * decimal.Parse(txt_interestrate.Text) * diffdays / 100 / 30),2).ToString();
            }
        }

        private void txt_receiptamount_TextChanged(object sender, EventArgs e)
        {
            if(txt_receiptamount.Text == "")
            {
                this.ShowErrorDialog2("请输入收款金额.");
                return;
            }
            if (!IsValidCurrency(txt_receiptamount.Text))
            {
                return;
            }
            if (dt_receiptdate.Value != null)
            {
                DateTime odt = dt_duedate.Value;
                int diffdays = (dt_receiptdate.Value - odt).Days;
                if (diffdays <= 0)
                {
                    diffdays = 0;
                }
                txt_overduedays.Text = diffdays.ToString();
                txt_interest.Text = Math.Round((decimal.Parse(txt_receiptamount.Text) * decimal.Parse(txt_interestrate.Text) * diffdays / 100 / 30), 2).ToString();
            }
        }

        private void txt_interestrate_TextChanged(object sender, EventArgs e)
        {
            if (txt_interestrate.Text == "")
            {
                this.ShowErrorDialog2("请输入利率.");
                return;
            }
            if (dt_receiptdate.Value != null)
            {
                DateTime odt = dt_duedate.Value;
                int diffdays = (dt_receiptdate.Value - odt).Days;
                if (diffdays <= 0)
                {
                    diffdays = 0;
                }
                txt_overduedays.Text = diffdays.ToString();
                txt_interest.Text = Math.Round((decimal.Parse(txt_receiptamount.Text) * decimal.Parse(txt_interestrate.Text) * diffdays / 100 / 30), 2).ToString();
            }
        }

        private void cb_company_SelectedIndexChanged(object sender, EventArgs e)
        {
            if(cb_company.SelectedText == "")
            {
                return;
            }
            if (receipt != null )
            {
                if(receipt.parentid > 0)
                {
                    //指定发货单
                    DataTable dt = MySQLHelper.ExecuteQuery("SELECT * FROM tbl_delivery where id = " + receipt.parentid);
                    if (dt.Rows.Count > 0)
                    {
                        DataRow row = dt.Rows[0];
                        decimal remainamount = 0;
                        if (decimal.TryParse(row["remainamount"].ToString(), out remainamount))
                        {
                            txt_remainamount.Text = Math.Round(remainamount, 2).ToString();
                            dt_duedate.Value = (DateTime)row["duedate"];

                            List<dynamic> items = new List<dynamic>();
                            items.Add(new
                            {
                                Id = long.Parse(row["id"].ToString()),
                                Duedate = row["duedate"].ToString(),
                                Remainamount = decimal.Parse(row["remainamount"].ToString()),
                                Display = (DateTime.Parse(row["duedate"].ToString()).ToString("yyyy-MM-dd") + "|" + row["remainamount"].ToString())
                            });

                            // 绑定到UIComboBox
                            cb_delist.DataSource = items;
                            cb_delist.DisplayMember = "Display";
                            cb_delist.ValueMember = "Id";
                            return;
                        }

                    }
                }else if(receipt.parentid == 0)
                {
                    //指定期初数
                    DataTable dt = MySQLHelper.ExecuteQuery("SELECT * FROM tbl_company where name = '" + receipt.companyname + "'");
                    if (dt.Rows.Count > 0)
                    {
                        DataRow row = dt.Rows[0];
                        decimal initalamount = 0;
                        if (decimal.TryParse(row["initalamount"].ToString(), out initalamount))
                        {
                            txt_remainamount.Text = Math.Round(initalamount, 2).ToString();
                            dt_duedate.Value = DateTime.Now;

                            List<dynamic> items = new List<dynamic>();
                            items.Add(new
                            {
                                Id = long.Parse(row["id"].ToString()),
                                Duedate = DateTime.Now.ToString(),
                                Remainamount = decimal.Parse(row["initalamount"].ToString()),
                                Display = "期初数|" + row["initalamount"].ToString()
                            });

                            // 绑定到UIComboBox
                            cb_delist.DataSource = items;
                            cb_delist.DisplayMember = "Display";
                            cb_delist.ValueMember = "Id";
                            return;
                        }

                    }
                }
                
            }
            else
            {
                JArray ars = new JArray();
                DataTable dt = MySQLHelper.ExecuteQuery("SELECT * FROM tbl_company where name = '" + cb_company.SelectedText + "'");
                if (dt.Rows.Count > 0)
                {
                    DataRow row = dt.Rows[0];
                    decimal initalamount = 0;
                    if (decimal.TryParse(row["initalamount"].ToString(), out initalamount))
                    {
                        if (initalamount != 0)
                        {
                            JObject tjson = new JObject();
                            tjson.Add("id", 0);
                            tjson.Add("deliverdate", "");
                            tjson.Add("duedate", "期初数");
                            tjson.Add("remainamount", initalamount);
                            tjson.Add("display", "期初数|" + initalamount);
                            ars.Add(tjson);
                            //txt_remainamount.Text = Math.Round(initalamount, 2).ToString();
                            //dt_duedate.Value = DateTime.Now;
                            //return;
                        }
                    }

                }
                //从发货单取值
                dt = MySQLHelper.ExecuteQuery("SELECT * FROM tbl_delivery where companyname = '" + cb_company.SelectedText + "' and remainamount > 0 order by duedate");
                if (dt.Rows.Count > 0)
                {
                    /*DataRow row = dt.Rows[0];
                    decimal remainamount = 0;
                    if (decimal.TryParse(row["remainamount"].ToString(), out remainamount))
                    {
                        if (remainamount > 0)
                        {
                            txt_remainamount.Text = Math.Round(remainamount, 2).ToString();
                            dt_duedate.Value = (DateTime)row["duedate"];
                            return;
                        }
                    }*/
                    foreach (DataRow row in dt.Rows)
                    {
                        JObject tjson = new JObject();
                        tjson.Add("id", long.Parse(row["id"].ToString()));
                        tjson.Add("deliverdate", row["deliverdate"].ToString());
                        tjson.Add("duedate", row["duedate"].ToString());
                        tjson.Add("remainamount", decimal.Parse(row["remainamount"].ToString()));
                        tjson.Add("display", DateTime.Parse(row["duedate"].ToString()).ToString("yyyy-MM-dd") + "|" + decimal.Parse(row["remainamount"].ToString()));
                        ars.Add(tjson);
                    }
                }
                //txt_remainamount.Text = "0.00";
                dt_duedate.Value = DateTime.Now;
                if(ars.Count == 0)
                {
                    cb_delist.DataSource = null;
                    return;
                }
                // 转换为List<dynamic>或创建特定类
                List<dynamic> items = new List<dynamic>();
                foreach (var item in ars)
                {
                    items.Add(new
                    {
                        Id = (long)item["id"],
                        Duedate = (string)item["duedate"],
                        Remainamount = (decimal)item["remainamount"],
                        Display = (string)item["display"]
                    });
                }

                // 绑定到UIComboBox
                cb_delist.DataSource = items;
                cb_delist.DisplayMember = "Display";
                cb_delist.ValueMember = "Id";
            }
            
        }

        private void dt_duedate_ValueChanged(object sender, DateTime value)
        {
            if (dt_receiptdate.Value != null)
            {
                DateTime odt = dt_duedate.Value;
                int diffdays = (dt_receiptdate.Value - odt).Days;
                if (diffdays <= 0)
                {
                    diffdays = 0;
                }
                txt_overduedays.Text = diffdays.ToString();
                txt_interest.Text = Math.Round((double.Parse(txt_receiptamount.Text) * double.Parse(txt_interestrate.Text) * diffdays / 100 / 30), 2).ToString();
            }
        }

        private void cb_delist_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cb_delist.SelectedItem != null)
            {
                // 获取选中的动态对象
                dynamic selectedItem = cb_delist.SelectedItem;

                // 获取各个属性值
                long id = selectedItem.Id;
                string dueDate = selectedItem.Duedate;
                decimal remainAmount = selectedItem.Remainamount;
                if(dueDate == "期初数")
                {
                    dt_duedate.Value = DateTime.Now;
                }
                else
                {
                    dt_duedate.Value = DateTime.Parse(dueDate);
                }
                
                txt_remainamount.Text = remainAmount.ToString();
                txt_parentid.Text = id.ToString();
            }
        }

        public bool IsValidCurrency(string input)
        {
            // 尝试解析字符串为decimal
            return decimal.TryParse(
                input,
                NumberStyles.Number | NumberStyles.AllowCurrencySymbol,
                CultureInfo.InvariantCulture,
                out _
            );
        }
    }
}
